package com.cloudeasy.post.service;

import com.cloudeasy.api.enums.ResultCodeEnum;
import com.cloudeasy.api.exception.CloudEasyException;
import com.cloudeasy.api.util.SnowFlake;
import com.cloudeasy.post.dao.repository.VoteRepository;
import com.cloudeasy.post.po.Vote;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@Transactional(rollbackFor = Exception.class)
public class VoteService {
    private final ReplyService replyService;

    private final VoteRepository voteRepository;

    private final SnowFlake snowFlake;

    public VoteService(@Lazy ReplyService replyService, VoteRepository voteRepository, SnowFlake snowFlake) {
        this.replyService = replyService;
        this.voteRepository = voteRepository;
        this.snowFlake = snowFlake;
    }

    /**
     * 点赞评论
     *
     * @param userId  用户Id
     * @param replyId 评论Id
     * @param type    类型
     * @return {@link Boolean}
     */
    public Boolean like(String userId, String replyId, Integer type) {
        Optional<Vote> voteOptional = voteRepository.findByUserIdAndReplyId(userId, replyId);
        if (voteOptional.isPresent()) {
            throw new CloudEasyException(ResultCodeEnum.REPEAT_ERROR);
        }
        replyService.like(replyId, type);
        String id = String.valueOf(snowFlake.nextId());
        Vote vote = Vote.builder()
                .id(id)
                .userId(userId)
                .replyId(replyId)
                .type(type)
                .build();
        voteRepository.save(vote);
        return true;
    }

    /**
     * 移除点赞评论
     *
     * @param userId  用户Id
     * @param replyId 评论Id
     * @return {@link Boolean}
     */
    public Boolean removeLike(String userId, String replyId) {
        Optional<Vote> voteOptional = voteRepository.findByUserIdAndReplyId(userId, replyId);
        if (!voteOptional.isPresent()) {
            throw new CloudEasyException(ResultCodeEnum.REPEAT_ERROR);
        }
        Vote vote = voteOptional.get();
        replyService.removeLike(replyId, vote.getType());
        voteRepository.deleteById(vote.getId());
        return true;
    }

    /**
     * 根据用户Id查询所有记录
     *
     * @param userId 用户Id
     * @return {@link List<Vote>}
     */
    public List<Vote> getLikeByUserId(String userId) {
        return voteRepository.findAllByUserId(userId);
    }
}
